﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

using Aliphant.Interfaces;

namespace Aliphant.Mvvm.XEvent
{
    public class XModuleCatalog : IModuleCatalog
    {
        public string ModuleDir { get; set; } = string.Empty;

        public void Register(IUIContainer container, IDiContainer dicontainer)
        {
            if (string.IsNullOrEmpty(ModuleDir))
            {
                return;
            }

            var files = Directory.GetFiles(ModuleDir, "*.dll", SearchOption.TopDirectoryOnly);
            foreach (var dll in files)
            {
                // 加载程序集
                Assembly assembly = Assembly.LoadFrom(dll);
                // 获取IModule类型
                var moduleTypes = assembly.GetTypes()
                        .Where(t => t.IsClass &&
                                    !t.IsAbstract &&
                                    typeof(IModule).IsAssignableFrom(t))
                        .ToList();

                CreateModule(moduleTypes, dicontainer);

                // 获取IUIModule类型
                var uimoduleTypes = assembly.GetTypes()
                        .Where(t => t.IsClass &&
                                    !t.IsAbstract &&
                                    typeof(IUIModule).IsAssignableFrom(t))
                        .ToList();

                CreateUIModule(uimoduleTypes, container);
            }
        }

        private void CreateModule(List<Type> types, IDiContainer container)
        {
            foreach(var type in types)
            {
                // 创建实例
                object? obj = Activator.CreateInstance(type);
                if (obj is IModule uimodule)
                {
                    uimodule.Register(container);
                }
            }
        }

        private void CreateUIModule(List<Type> types, IUIContainer container)
        {
            foreach (var type in types)
            {
                // 创建实例
                object? obj = Activator.CreateInstance(type);
                if (obj is IUIModule uimodule)
                {
                    uimodule.Register(container);
                }
            }
        }
    }
}
